package com.masterclient.app.businessmodule.usermodule.login.index;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.OkHttpUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.enums.WXSendTypeEnum;
import com.eoner.middlelib.eventbus.enums.WXSendTypeManager;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.eoner.middlelib.eventbus.event.WXSendCancelEvent;
import com.eoner.middlelib.eventbus.event.WXSendFailedEvent;
import com.eoner.middlelib.eventbus.event.WXSendSuccessEvent;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.businessmodule.usermodule.login.BindPhoneActivity;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindData;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviteInfoData;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginBean;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginSuccessData;
import com.masterclient.app.businessmodule.usermodule.login.contract.PwdLoginContract;
import com.masterclient.app.businessmodule.usermodule.login.contract.PwdLoginPresenter;
import com.masterclient.app.businessmodule.usermodule.login.dialog.InviteDialog;
import com.masterclient.app.businessmodule.usermodule.login.invite.BindInviteActivity;
import com.masterclient.app.businessmodule.usermodule.login.util.LoginUtil;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.internal.platform.Platform;

/**
 * 作者：sean
 * 创建时间：2018/3/8 16:54
 * 功能说明：
 */
@Route(path = AroutePath.PWD_LOGIN_FRAGMENT)
public class PwdLoginActivity extends FCBusinessActivity<PwdLoginPresenter> implements PwdLoginContract.View {

    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.scroll)
    ScrollView scrollView;
    @BindView(R.id.view_agreement)
    View viewAgreement;

    @Autowired(name = "mobile")
    String mobile = "";

    String auth_type = "weixin", union_id = "";
    private boolean isSelected = false;
    private String rewardId = "";
    SPUtils spUtils;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(nopeAnimator != null && nopeAnimator.isRunning()){
                nopeAnimator.end();
            }
        }
    };
    private IWXAPI api;

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int requireGetLayoutId() {
        return R.layout.fragment_pwd_login;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setVisibility(View.GONE);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        spUtils = SPUtils.getInstance();
        api = WXAPIFactory.createWXAPI(getActivity(), WeiXinManager.APP_ID,true);
        api.registerApp(WeiXinManager.APP_ID);

        tvLogin.setClickable(false);

        showSoftInput(etPhone);
        initEtHint(etPhone,"请输入手机号码",13);
        initEtHint(etPwd,"请输入登录密码",13);
        scrollToShowSubmitBtn(scrollView);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence == null || charSequence.length() == 0) {
                    etPhone.setTypeface(Typeface.DEFAULT);
                    return;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < charSequence.length(); i++) {
                    if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(charSequence.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(charSequence.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    etPhone.setText(sb.toString());
                    etPhone.setSelection(index);
                }

                if (etPhone.getText().toString().length() > 0) {
                    Utils.setDin(etPhone, mContext);
                } else {
                    etPhone.setTypeface(Typeface.DEFAULT);
                }

                if (etPhone.getText().toString().trim().replace(" ","").length() == 11 && etPwd.getText().toString().trim().length() >= 6) {
                    tvLogin.setClickable(true);
                    tvLogin.setBackgroundResource(R.drawable.login_able_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                } else {
                    tvLogin.setClickable(false);
                    tvLogin.setBackgroundResource(R.drawable.login_unable_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence == null || charSequence.length() == 0) {
                    etPwd.setTypeface(Typeface.DEFAULT);
                    return;
                }
                if (etPwd.getText().toString().length() > 0) {
                    Utils.setDin(etPwd, mContext);
                } else {
                    etPwd.setTypeface(Typeface.DEFAULT);
                }

                if (charSequence.length() >= 6 && etPhone.getText().toString().trim().replace(" ","").length() == 11) {
                    tvLogin.setClickable(true);
                    tvLogin.setBackgroundResource(R.drawable.login_able_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                } else {
                    tvLogin.setClickable(false);
                    tvLogin.setBackgroundResource(R.drawable.login_unable_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etPhone.setOnClickListener(view -> scrollToShowSubmitBtn(scrollView));
        etPhone.setOnTouchListener((view, motionEvent) -> {
            scrollToShowSubmitBtn(scrollView);
            return false;
        });
        etPwd.setOnClickListener(view -> scrollToShowSubmitBtn(scrollView));
        etPwd.setOnTouchListener((view, motionEvent) -> {
            scrollToShowSubmitBtn(scrollView);
            return false;
        });

        if(!TextUtils.isEmpty(mobile)){
            etPhone.setText(mobile);
            etPhone.setSelection(etPhone.getText().toString().length());
        }
    }



    /**
     * 使滚动条滚动至指定位置（垂直滚动）
     *
     * @param scrollView 要滚动的ScrollView
     * @param to         滚动到的位置
     */
    protected void scrollVertical(final ScrollView scrollView, final int to) {
        scrollView.postDelayed(() -> scrollView.scrollTo(0, to),100);
    }

    /**
     * 使ScrollView滚动至底部，显示Submit按钮
     *
     * @param scrollView 要滚动的scrollView
     */
    protected void scrollToShowSubmitBtn(final ScrollView scrollView) {
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        scrollView.postDelayed(() -> scrollVertical(scrollView, scrollView.getHeight()), 100);
    }

    String mobile_x;
    @OnClick({R.id.tv_forget, R.id.tv_agreement, R.id.tv_login, R.id.ll_wechat,
             R.id.rl_back,R.id.ll_login_by_code,R.id.iv_check_btn})
    void onClick(View view) {
        Platform platform;
        switch (view.getId()) {
            case R.id.rl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
            case R.id.tv_forget:
                mobile_x = etPhone.getText().toString().trim().replace(" ","");
//                if(!UtilCollection.isMobileNum(mobile_x)){
//                    mobile_x = "";
//                }
                Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.FORGET_PED_FRAGMENT).withString("mobile",mobile_x).navigation();
                FragmentHostActivity.openFragment(Objects.requireNonNull(getActivity()), fragment);
                break;
            case R.id.ll_login_by_code:
                mobile_x = etPhone.getText().toString().trim().replace(" ","");
//                if(!UtilCollection.isMobileNum(mobile_x)){
//                    mobile_x = "";
//                }

                ARouter.getInstance().build(FCRouterPath.USER_LOGIN_PATH).withString("mobile",mobile_x).navigation();
                getActivity().finish();
                break;
            case R.id.tv_agreement:
                startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", SystemConfigStorage.getInstance().getServiceRuleUrl()}, {"title", "中华大师汇服务协议"}});
                break;

            case R.id.tv_login:
                if (!isSelected){
                    startLeftAndRightShake();
                    mHandler.sendEmptyMessageDelayed(0,500);
                    ToastUtil.showToast("请先同意《用户服务协议》");
                    return;
                }
                String mobile = etPhone.getText().toString().trim().replace(" ","");
                String pwd = etPwd.getText().toString().trim();
//                &&StringUtils.isPhoneNum(mobile)
                if (!TextUtils.isEmpty(mobile) && StringsUtils.isPhoneNum(mobile)) {
                    if (!TextUtils.isEmpty(pwd) && pwd.length() >= 6) {
                        mPresenter.pwdLogin(mobile, pwd);
                    } else {
                        ToastUtil.showToast("密码不能少于6位字符");
                    }
                } else {
                    ToastUtil.showToast("手机号码格式有误");
                }
                break;
            case R.id.ll_wechat:
                if (!isSelected){
                    startLeftAndRightShake();
                    mHandler.sendEmptyMessageDelayed(0,500);
                    ToastUtil.showToast("请先同意《用户服务协议》");
                    return;
                }
                if (api.isWXAppInstalled()) {
                    WXSendTypeManager.getInstance().setWxType(WXSendTypeEnum.PW_LOGIN_EVENT_TYPE);
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "none";
                    api.sendReq(req);
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.iv_check_btn:
                if (isSelected){
                    isSelected = false;
                    ivCheck.setImageResource(R.mipmap.icon_lg_no_sel);
                }else {
                    isSelected = true;
                    ivCheck.setImageResource(R.mipmap.icon_lg_sel);
                }
                break;
        }

    }

    @Override
    public void loginSuccess(LoginBean.LoginData data) {
        showToast("登录成功");
        hideSoftInput(etPwd);
        SPUtils.getInstance().put(Config.CUSTOMERID, data.getSh_customer_id());
        SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getSh_token());
        UserDataManager.getInstance().updateUserStatus(data.getSh_is_disable());
        EventBusManager.post(EventBusManager.createLoginSuccessEvent());
        EventBusManager.post(EventBusManager.createHomeRefreshEvent());
//        Config.CUSTOMER_ID = data.getSh_customer_id();
//        Config.TOKEN = data.getSh_token();
//        setResult(101);
        setResult();
        getActivity().finish();
        if ("1".equals(data.getSh_is_disable())){
            UtilActivity.finishStartNum(0,UtilActivity.getActivitySize());
            ARouter.getInstance().build(AroutePath.BAN_ACCOUNT_ACTIVITY)
                    .withString("content",data.getSh_freeze_reason()).navigation();
        }else {
            if (!UtilActivity.isCurActivity("MainActivity")){
                startActivitryWithBundle(MainActivity.class,null);
            }
        }
    }

    @Override
    public void loginFailed(String msg, String failReason) {
        ToastUtil.showToast(msg);
//        startLeftAndRightShake();
//        mHandler.sendEmptyMessageDelayed(0,500);
    }

    ObjectAnimator nopeAnimator;
    private void startLeftAndRightShake() {
        //左右移动
        nopeAnimator = LoginUtil.nope(viewAgreement);
        nopeAnimator.setRepeatCount(ValueAnimator.INFINITE);
        nopeAnimator.start();
    }


    @Override
    public void authLoginData(boolean isOther, LoginSuccessData data,String msg) {
        baseHiddenCommitLoading();
        spUtils.put(Config.QUICK_VERIFY_TIME,0l);
        login_success_next(isOther,data);
    }

    LoginSuccessData data;
    private void login_success_next(boolean isOther, LoginSuccessData data) {
        
        if(!TextUtils.isEmpty(data.getCustomer_id())){
            SPUtils.getInstance().put(Config.CUSTOMERID_TEMP, data.getCustomer_id());
        }
        if(!TextUtils.isEmpty(data.getToken())){
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN_TEMP, data.getToken());
        }
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        this.data = data;
        if (data.getInviter_code_select_pop() != null && data.getInviter_code_select_pop().bindInviterCode != null){
            rewardId = data.getInviter_code_select_pop().bindInviterCode.rewardId;
        }
        if (data.isIs_disable()) {
            SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
            UtilActivity.finishStartNum(0, UtilActivity.getActivitySize());
            ARouter.getInstance().build(AroutePath.BAN_ACCOUNT_ACTIVITY)
                    .withString("content", data.getFreeze_reason()).navigation();
        } else if (data.isNeed_bind_phone()) {//需要绑定手机号
            Intent intent = new Intent(getActivity(), BindPhoneActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("auth_type", auth_type);
            bundle.putString("union_id", union_id);
            bundle.putString("nick_name", nick_name);
            bundle.putString("headimgurl", headimgurl);
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("login_success_data", data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindPhoneActivity.REQUEST_CODE);
        } else if (data.isIs_show_code_select_pop() || data.isIs_show_user_info_pop()) {
            //绑定邀请人弹窗
            mobile = data.getMobile();
            //TODO:fix
            //绑定邀请人弹窗
            Intent intent = new Intent(getActivity(), BindInviteActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("auth_type", auth_type);
            bundle.putString("phone", mobile);
            bundle.putString("union_id", union_id);
            bundle.putString("nick_name", nick_name);
            bundle.putString("headimgurl", headimgurl);
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("lg_data",data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindInviteActivity.REQUEST_CODE);


        }else {
            //已绑定
            login_success_convert();
        }
    }

    private void login_success_convert() {
        showToast("登录成功");
        SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
        SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        EventBusManager.post(EventBusManager.createLoginSuccessEvent());
        EventBusManager.post(EventBusManager.createHomeRefreshEvent());
        setResult();
        getActivity().finish();

        if (!UtilActivity.isCurActivity("MainActivity")) {
            startActivitryWithBundle(MainActivity.class, null);
        }
    }

    private InviteDialog dialog;
    private void show_pop_dialog(LoginSuccessData data) {
        if (dialog == null) {
            dialog = new InviteDialog(getActivity(), new InviteDialog.OnChooseListener() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void getByInviteCode(String invite_code) {
                    mPresenter.getInviteInfo(invite_code);
                }

                @Override
                public void confirm(String inviteCode) {
                    //dialog.dismiss();
                    baseShowCommitLoading("登录中");
                    mPresenter.authBind(auth_type,mobile, union_id,inviteCode,Config.uid,nick_name,headimgurl,
                            data.getNonce(),SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP),rewardId);
                }

                @Override
                public void skip_login() {
                    login_success_convert();
                }
            });
        }
        dialog.show();
        dialog.setData(data);
    }


    @Override
    public void authLoginError(String msg, String failReason ) {
        if (failReason != null)
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void showInviteInfo(InviteInfoData inviteInfoData) {
        rewardId = "";
        dialog.refreshInviteInfo(inviteInfoData,"");
    }

    @Override
    public void showInviteInfoFail(String msg) {
        dialog.refreshErrorInfo(msg);
    }

    @Override
    public void authBindSuccess(String code,AuthBindData data,String msg, String inviteCode) {
        UserDataManager.getInstance().updateInviteCode(inviteCode);
        if ("30000".equals(code)){
            rewardId = data.getInviteInfo().getReward_id();
            dialog.refreshInviteInfo(data.getInviteInfo(),data.getNotice());
        }else {
            if(dialog != null){
                dialog.dismiss();
            }
            if (data != null) {
                if(!TextUtils.isEmpty(data.getCustomer_id())){
                    SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
                }else {
                    SPUtils.getInstance().put(Config.CUSTOMERID, SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP));
                }
                if(!TextUtils.isEmpty(data.getToken())){
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
                }else{
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN_TEMP));
                }
            }
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());

            setResult();
            getActivity().finish();
            if (!UtilActivity.isCurActivity("MainActivity")){
                startActivitryWithBundle(MainActivity.class,null);
            }
        }
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void authBindFailded(String msg) {

        baseHiddenCommitLoading();
        showToast(msg);
    }

    private void setResult() {
        if (getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
            Bundle bundle = getActivity().getIntent().getExtras();
            String result = bundle.getString("result_code");
            if (!TextUtils.isEmpty(result)) {
                getActivity().setResult(Integer.valueOf(result));
            }
        }
    }

    String nick_name,headimgurl;
    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      微信回调事件
    //
    /////////////////////////////////////////////////////////////////////////////////
    /**
     * 成功
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendSuccess(WXSendSuccessEvent successEvent) {
        if (successEvent.getWxType() == WXSendTypeEnum.PW_LOGIN_EVENT_TYPE) {
            String code = successEvent.getCode();
            //获取用户信息
            getAccessToken(code);
        }
    }

    /**
     * 取消
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendCancel(WXSendCancelEvent cancelEvent) {

    }

    /**
     * 失败
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendFailed(WXSendFailedEvent failedEvent) {

    }


    private void getAccessToken(String code) {
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(WeiXinManager.APP_ID)
                .append("&secret=")
                .append(WeiXinManager.SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //获取个人信息
                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
                OkHttpUtils.ResultCallback<String> reCallback = new OkHttpUtils.ResultCallback<String>() {
                    @Override
                    public void onSuccess(String responses) {
                        try {
                            JSONObject jsonObject = new JSONObject(responses);
                            nick_name = jsonObject.getString("nickname");
                            headimgurl = jsonObject.getString("headimgurl");
                            union_id = jsonObject.getString("unionid");

                            if (getActivity() != null) {
                                ((getActivity())).runOnUiThread(() -> {
                                    baseShowCommitLoading("授权登录中");
                                });
                            }
                            mPresenter.authLogin(auth_type,headimgurl,nick_name,union_id,Config.uid,"");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
                    }
                };
                OkHttpUtils.get(getUserInfo, reCallback);
            }

            @Override
            public void onFailure(Exception e) {
                Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            }
        };
        OkHttpUtils.get(loginUrl.toString(), resultCallback);
    }

    //TODO:通知登录成功
    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BindInviteActivity.REQUEST_CODE) {
            if (resultCode == BindInviteActivity.BIND_SUC_CODE) {
                setResult();
                getActivity().finish();
                if (!UtilActivity.isCurActivity("MainActivity")) {
                    startActivitryWithBundle(MainActivity.class, null);
                }
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
